package com.starblink.discover.ui

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.appsflyer.AppsflyerManager
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.config.ColdLaunchConfig
import com.starblink.android.basic.ext.commContext
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.network.config.PostConfig.postRecommendPage
import com.starblink.android.basic.util.ImageUtils
import com.starblink.basic.storage.SkStorage
import com.starblink.rocketreserver.FetchRecommendPostV2Query
import com.starblink.rocketreserver.FetchResourceConfigQuery
import com.starblink.rocketreserver.fragment.PostF
import com.starblink.rocketreserver.type.PostRecommendQueryParam
import kotlinx.coroutines.launch

class NavDiscoverVM : BaseViewModel() {
    var mList: MutableLiveData<ArrayList<Any>> = MutableLiveData(arrayListOf())
    var postList: ArrayList<PostF> = arrayListOf()
    var pageNo: Int = 0
    var hasBanner: Boolean = false
    var starCardNum: Int = 0
    val pageSize = 20

    /**
     * initData 初始化数据
     */
    fun getRecommendPost(initData: Boolean = false) {
        viewModelScope.launch {
            if (initData) {
                hasBanner = false
                starCardNum = 0
                pageNo = 0
                postList.clear()

                // 仅刷新页面时，加载Banner数据
                val res = SkGqlClient.skQuery(
                    FetchResourceConfigQuery(
                        operationFeaturedSize = Optional.present(4),
                        resourceType = Optional.present(1),
                    )
                )
                if (res?.data != null && res.data!!.fetchResourceConfig != null && res.data!!.fetchResourceConfig!!.isNotEmpty()) {
                    hasBanner = true
                    if (mList.value!!.isNotEmpty()) {
                        mList.value!!.clear()
                    }
                    mList.value?.add(0, res.data!!.fetchResourceConfig!!)
                    mList.value = mList.value
                }

//                hasBanner = true
//                val f: FetchResourceConfigQuery.FetchResourceConfig =
//                    FetchResourceConfigQuery.FetchResourceConfig(
//                        "ResourceF",
//                        resourceF = ResourceF(
//                            "11",
//                            "11",
//                            "11",
//                            "https://cdn.sstatic.net/Img/teams/teams-illo-free-sidebar-promo.svg?v=47faa659a05e",
//                            "11",
//                            "11",
//                            "https://cdn.sstatic.net/Img/teams/teams-illo-free-sidebar-promo.svg?v=47faa659a05e",
//                            0,
//                            "11",
//                            "11"
//                        )
//                    )
//                val list: List<FetchResourceConfigQuery.FetchResourceConfig?> = listOf(f)
//
//                mList.value?.add(0, list)
//                mList.value = mList.value
//                Log.i("FetchResourceConfig","===00=$list")
            }

            val response = SkGqlClient.skQuery(
                FetchRecommendPostV2Query(
                    postParams = PostRecommendQueryParam(
                        sceneCode = 1, // 推荐场景编码 1 首页HOME_POST_FEED 3 相似 POST_SIMILAR
                        relatedPostId = Optional.Absent,
                        pageNo = postRecommendPage,
                        pageSize = pageSize,
                        advertiseId = if(AppsflyerManager.getADID().isNotEmpty()) Optional.present(AppsflyerManager.getADID()) else Optional.Absent,
                        clientTime = Optional.present(System.currentTimeMillis().toString()),
                        isReported = Optional.present(
                            SkStorage.getBoolean(
                                ColdLaunchConfig.PREFERENCE_CONFIG_CHOOSE_OR_NOT,
                                false
                            )
                        ), // 是否冷启动过
                        needStarCard = Optional.present(initData) // 仅初始化数据时，需要返回明星卡片
                    )
                )
            )

            if (response?.data != null && response.data!!.fetchRecommendPostV2 != null) {
                var postListTmp = arrayListOf<PostF>() // 仅保存Post数据
                var mixPosts = arrayListOf<Any>() // 保存Post+明星卡片数据，将服务器返回数据打平
                for (item in response.data!!.fetchRecommendPostV2!!) {
                    if (item?.type == 1 && item.post != null) {
                        // 1-普通POST
                        postListTmp.add(item.post!!.postF)
                        mixPosts.add(item.post!!.postF)
                        // 预加载图片
                        var imgUrl = item.post!!.postF.mainPic
                        ImageUtils.preloadImage(commContext(), imgUrl)
                    } else if (item?.type == 2 && item.starCard != null) {
                        // 2-明星卡片
                        starCardNum++
                        mixPosts.add(item.starCard!!)
                        // 预加载图片
                        val pics = mutableListOf<String>()
                        item.starCard!!.mainPic?.let { pics.add(it) }
                        item.starCard!!.otherPics?.let { urls ->
                            urls.forEach { pic -> pic?.let { pics.add(it) } }
                        }
                        if (pics.isNotEmpty()) {
                            ImageUtils.preloadImage(commContext(), pics)
                        }
                    }
                }
                postRecommendPage += 1
                postList.addAll(postListTmp)
                // 此处仅当initData=true，hasBanner=false，列表不为空时清空列表
                // 当hasBanner=true时，前面已经清空过列表
                if (initData && !hasBanner && mList.value!!.isNotEmpty()) {
                    mList.value!!.clear()
                }
                mList.value?.addAll(mixPosts)
                mList.value = mList.value
            } else {
                if (initData) {
                    mList.value!!.clear()
                    loadNoData()
                }
            }


//        if (initData) {
//            hasBanner = false
//            pageNo = 0
//            postList = arrayListOf()
//            viewModelScope.launch {
//                val res = SkGqlClient.skQuery(
//                    FetchResourceConfigQuery(
//                        operationFeaturedSize = Optional.present(4),
//                        resourceType = Optional.present(1),
//                    )
//                )
//                if (res?.data != null && res.data!!.fetchResourceConfig != null && res.data!!.fetchResourceConfig!!.isNotEmpty()) {
////                    if (initData && mList.value!!.isNotEmpty()) {
////                        mList.value!!.clear()
////                    }
//                    hasBanner = true
//                    bannerLD.postValue(res.data!!.fetchResourceConfig!!)
////                    mList.value?.add(0, res.data!!.fetchResourceConfig!!)
////                    mList.value = mList.value
//                }
//            }
//        }
//        viewModelScope.launch {
//            val response = SkGqlClient.skQuery(
//                FetchPostsQuery(
//                    postParams = PostRecommendQueryParam(
//                        1,
//                        relatedPostId = Optional.present(""),
//                        postRecommendPage,
//                        pageSize,
//                        advertiseId = Optional.present(""),
//                        clientTime = Optional.present(System.currentTimeMillis().toString()),
//                        isReported = Optional.present(false),
//                    ), isPostDetail = false
//                )
////                , showDefaultLoading = (initData && !refresh)
//
//            )
////            loadSuccess()
//            if (response?.data != null && response.data!!.fetchRecommendPost != null) {
//                var list1 = response.data!!.fetchRecommendPost
//                var list = arrayListOf<PostF>()
//                list1!!.forEach { e ->
//                    list.add(e.postF)
//                    var imgUrl = e.postF.mainPic
//                    ImageUtils.preloadImage(commContext(), imgUrl)
//                }
//                postRecommendPage += 1
//                postList.addAll(list)
////                if (initData && mList.value!!.size > 1) {
////                    mList.value!!.clear()
////                }
////                mList.value?.addAll(list)
////                mList.value = mList.value
//                recommendLD.postValue(list)
//            } else {
////                if (initData) {
////                    mList.value!!.clear()
////                    loadNoData()
////                }
//            }
//        }
        }
    }
}